<?php
/*
 * @Author: cwj
 * @Date: 2019-12-13 16:13:22
 * @LastEditTime: 2020-06-20 15:32:04
 * @LastEditors: Please set LastEditors
 * @Description: 修改 异步方式
 * @FilePath: /ahsmp_3/application/asmpasync/socket/SocketClient.php
 */
namespace app\asmpasync\socket;
class SocketClient
{

    private $socket;
    public $feedback = '';
    public $error_id = 0;
    public $err_msg = 0;
    public $sendStatus;
    function __construct($ip = '127.0.0.1', $port = 7921)
    {

        $context = stream_context_create([
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ]
        ]);
        $this->socket = @stream_socket_client( 'tlsv1.2://' . $ip . ':' . $port, $this->error_id, $this->err_msg, 10, STREAM_CLIENT_CONNECT, $context);
    }

    /**
     * @name: 发送信息
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-05-28 16:37:00
     */
    function sendMsg ($msg)
    {
        
        if ($this->error_id > 0)
        {
            return $msg;
        }

        fwrite($this->socket, $msg);

        $this->feedback();
        
        fclose($this->socket);
    }

    /**
     * @name: 返回信息
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-05-28 16:42:09
     */
    function feedback ()
    {
        $serverBack = fread($this->socket, 4096);

        $len = unpack('ilen', substr($serverBack, 0, 4));
        
        $data = substr($serverBack, 6, $len['len']);
        $Event = new \Jzzproto\Event();
        $Event->mergeFromString($data);
        
        $Result = $Event->getMessage();
        $message = $Result->unpack($Result->getValue());

        $return = $message->getMessage();
        $this->sendStatus = $message->getStatus();

        return $return;
    }
}